package com.sheenhan.gdemo.model

import android.graphics.Color
import androidx.lifecycle.LifecycleObserver
import com.amap.api.maps.MapView
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.DistanceItem
import com.amap.api.services.route.DistanceResult
import com.amap.api.services.route.DistanceSearch
import com.sheenhan.gdemo.PathSmoothTool
import com.amap.api.services.core.AMapException
import com.amap.api.services.route.DistanceSearch.DistanceQuery
import com.sheenhan.gdemo.R
import kotlinx.coroutines.flow.flow
import java.math.BigDecimal
import kotlin.math.log
import com.amap.api.maps.model.LatLng


class GDModel(map: MapView) : LifecycleObserver , DistanceSearch.OnDistanceSearchListener {

    var data = MutableLiveData<String>()

    private val TAG = "GDModel"
    private val map = map
    private var points = mutableListOf<LatLonPoint>()
    private var latLngs = mutableListOf<LatLng>()
    private val distanceSearch = DistanceSearch(map.context)
    private val distanceQuery = DistanceQuery()
    private var lastPoint: LatLonPoint? = null
    private var lastLatLng: LatLng? = null
    private var dis = 0f
    private val pathSmoothTool = PathSmoothTool()
    private lateinit var polylineOptions: PolylineOptions

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        val aMap = map.map
        aMap.maxZoomLevel = 21f
        aMap.minZoomLevel = 12f

        val locationClient = AMapLocationClient(map.context)
        val mLocationOptions = AMapLocationClientOption()
        mLocationOptions.isOnceLocation = false
        mLocationOptions.isMockEnable = false;
        mLocationOptions.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        locationClient.setLocationOption(mLocationOptions)
        locationClient.startLocation()
        mLocationOptions.isSensorEnable = false


        val myLocationStyle = MyLocationStyle()
        myLocationStyle.interval(1000)
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.navi_map_gps_locked))
        myLocationStyle.strokeColor(Color.argb(0 , 0 , 0 , 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0 , 0 , 0 , 0));// 设置圆形的填充颜色
        myLocationStyle.anchor(0.5f , 0.576f); // 这个数值是根据我的图片显示的时候计算的，最好是0.5 0.5
        myLocationStyle.strokeColor(Color.argb(19 , 73 , 190 , 255));// 设置圆形的边框颜色 rgba(73, 190, 255, 19)
        myLocationStyle.radiusFillColor(Color.argb(19 , 73 , 190 , 255));// 设置圆形的填充颜色

        aMap.myLocationStyle = myLocationStyle
        aMap.isMyLocationEnabled = true


        val mpathSmoothTool = PathSmoothTool()
        //设置平滑处理的等级
        mpathSmoothTool.intensity = 4
        val pathoptimizeList = mpathSmoothTool.pathOptimize(latLngs)
        polylineOptions = PolylineOptions().width(20f).addAll(pathoptimizeList).color(Color.GREEN).zIndex(0f)
        aMap.addOnMyLocationChangeListener {
            val latLng = LatLng(it.latitude , it.longitude)
            latLngs.add(latLng)
            polylineOptions.points = latLngs
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs) , 200))
            aMap.addPolyline(polylineOptions)


            if (lastLatLng != null) {
                val distance = AMapUtils.calculateLineDistance(lastLatLng , latLng)
                dis += distance
                data.postValue(dis.toString())
            }
            lastLatLng = latLng

        }
        distanceSearch.setDistanceSearchListener(this)

    }

    fun juli() {

        val latLng1 = LatLng(39.136505 , 117.187988)
        val latLng2 = LatLng(39.136682 , 117.187979)
        latLngs.add(latLng1)
        latLngs.add(latLng2)
        polylineOptions.points = latLngs

        map.map.addPolyline(polylineOptions)
        map.map.animateCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs) , 200))
    }


    override fun onDistanceSearched(distanceResult: DistanceResult , errorCode: Int) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            try {
                val distanceItems: List<DistanceItem> = distanceResult.distanceResults
                for (item in distanceItems) {
                    dis += item.distance
                }
                data.postValue(dis.toString())
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        map.onResume()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        map.onPause()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestory() {
        map.onDestroy()
    }

    private fun getBounds(pointlist: List<LatLng>?): LatLngBounds? {
        val b = LatLngBounds.builder()
        if (pointlist == null) {
            return b.build()
        }
        for (i in pointlist.indices) {
            b.include(pointlist[i])
        }
        return b.build()
    }


}